<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Service;
use App\Models\Staff;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use TemplateService;

class OrderController extends Controller
{
    public function __construct()
    {
        View::addNamespace('templates', public_path('templates'));
        $this->defineTemplate();
    }

    protected function defineTemplate()
    {
        //获取已经安装的模板的name:default，默认为default类型
        $name = TemplateService::getActiveTemplate();
        try {
            //为模板添加指向的路径
            \View::addLocation(base_path("templates/{$name}"));
        } catch (Exception $e) {
            abort('404', '模板文件不存在');
        }
    }

    public function index()
    {
        $staffs = Staff::where('gold', true)->get();
        return view('order.index', compact('staffs', $staffs));
    }

    public function create(Order $order)
    {
        $services = Service::all();
        return view('order.create', ['order' => $order, 'services' => $services]);
    }


    public function store(Request $request, Order $order)
    {
//        return dd($request->toArray());
        $request->validate([
            'service_id' => ['required'],
            'name' => ['required'],
            'address' => ['required'],
            'mobile' => ['required', 'regex:/^1\d{10}$/']
        ], [
            'service_id.required' => '请选择服务类型',
            'name.required' => '请输入姓名',
            'address.required' => '请输入地址',
            'mobile.required' => '请输入手机号',
            'mobile.regex' => '手机号格式不正确'
        ]);


        $order = Order::create($request->input());
//发送短信预约
//        CodeService::send($order);
        $order->overtime = Carbon::now()->modify('+3 days');
        $order->save();
        return back()->with('success', "预约成功，你的预约标号为:" . $order->id . '号！');
    }
}

